<?php
/**
 * Created by PhpStorm.
 * User: sunzexin
 * Date: 2018/3/19
 * Time: 09:50
 */

namespace App\Http\Logics\MiniProgram;


use App\Cart;
use App\Http\Logics\BaseLogic;

class CartLogic extends BaseLogic
{
    public static function createCart($data)
    {
        $response = self::getUserIdByLoginSession($data['loginSession']);
        if ($response->code) {
            return self::response($response->code);
        }
        $user_id = $response->data;

        // 查找一下购物车原本是不是有本商品
        $cart = Cart::where(function($query) use ($user_id, $data){
            $query->where('user_id', $user_id);
            $query->where('goods_id', $data['goods_id']);
        })->first();

        if (empty($cart)){
            $cart = new Cart();
            $cart->goods_id = $data['goods_id'];
            $cart->user_id = $user_id;
            $cart->num = $data['num'];
            if (!$cart->save()){
                return self::response(self::OBJECT_DELETE_FAILD);
            }
        }else{
            $cart->num += $data['num'];
            if (!$cart->save()){
                return self::response(self::OBJECT_SAVE_FAIL);
            }
        }

        return self::response(self::SUCCESS);
    }

    public static function deleteCart($data)
    {
        $cart = Cart::find($data['cart_id']);
        if (!$cart->forceDelete()){
            return self::response(self::OBJECT_DELETE_FAILD);
        }
        return self::response(self::SUCCESS);
    }

    public static function getCartList($data)
    {
        $response = self::getUserIdByLoginSession($data['loginSession']);
        if ($response->code) {
            return self::response($response->code);
        }
        $user_id = $response->data;
        $cart = Cart::with(['goods' => function($query){
            $query->withTrashed();
        }, 'goods.product' => function($query){
            $query->withTrashed();
        }])->where(function($query) use ($user_id){
            $query->where('user_id', $user_id);
        })->get();
        if (empty($cart)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        return self::response(self::SUCCESS, $cart);
    }

    public static function changeCartNum($data)
    {
        $cart = Cart::find($data['cart_id']);
        if (empty($cart)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        $cart->num += $data['num'];
        if (!$cart->save()){
            return self::response(self::OBJECT_SAVE_FAIL);
        }
        return self::response(self::SUCCESS, $cart->num);
    }
}